package com.raising.modules.sys.service;

import com.raising.StaticParam;
import com.raising.framework.entity.ResultVo;
import com.raising.framework.service.CrudService;
import com.raising.modules.sys.dao.DictDao;
import com.raising.modules.sys.dao.DictItemDao;
import com.raising.modules.sys.entity.Dict;
import com.raising.modules.sys.entity.DictItem;
import com.raising.utils.JStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* 字典表 Service层
* @author gaoy
* @version 1.0
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class DictService extends CrudService<DictDao, Dict> {
	@Autowired
	private DictItemDao dictItemDao;
	/**
	 * 保存字典表与明细表
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public int saveDictAndItems(Dict dict){
		List<DictItem> items = dict.getDictItemList();
		if(dict.getIsNewId()){
			//新建
			dict.setStatus(StaticParam.VALID_STRING);
			dict.preInsert(null);
			dict.setId(this.nextId());
			dao.insert(dict);
		} else {
			//编辑
			DictItem item = new DictItem();
			item.setDictId(dict.getId());
			dictItemDao.deleteByParam(item);
			dict.preUpdate(null);
			dao.update(dict);
		}
		for(DictItem item:items){
			if(JStringUtils.isNotBlank(item.getValue())
					&& JStringUtils.isNotBlank(item.getLabel())){
				item.setId(this.nextId());
				item.setDictId(dict.getId());
				item.setDictValue(dict.getValue());
				item.setStatus(StaticParam.VALID_STRING);
				item.preInsert(null);
				if(JStringUtils.isBlank(item.getSort())){
					item.setSort("0");
				}
				dictItemDao.insert(item);
			}
		}
		return 1;
	}
	
	
	/**
	 * 删除数据-字典主表与从表【重写】 
	 * @author GY
	 */
	@Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo delete(String id) {
		DictItem dictItem = new DictItem();
		dictItem.setDictId(id);
    	dictItemDao.deleteByParam(dictItem);
    	return ResultVo.success().desc("删除成功").data(dao.delete(id));
    }
}
